package com.ruoyi.business.ocpxController;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.enums.SaveType;
import com.ruoyi.common.utils.EncrypDES;
import com.ruoyi.common.utils.GetUrlParam;
import com.ruoyi.common.utils.OtherUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.domain.vo.R;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;

@RestController
@RequestMapping("ownOCPXApi2")
public class OcpxNewController {

    @Autowired
    private RedisCache redisCache;

    private final static String CLASSESEN = "ocpx";

    private final static String CALLBACK_URLBASE = "http://c2.wkanx.com/tracking";

    private final static String SECRET = "51bce62df4df5a1e1f7f2775b5c3712e";



    @Log(title = "OCPX", businessType = BusinessType.ESCALATION, esIndex = "ocpx_log", saveType = SaveType.ES)
    @RequestMapping("/send")
    public Object send(HttpServletRequest request) throws Exception {
        String queryString = request.getQueryString();
        String channelId = request.getParameter("channelId");
        String dmpid = request.getParameter("dmpid");
        if(StringUtils.isBlank(channelId) || "null".equals(channelId)){
            return R.failure().msg("channelId不能为空");
        }
        if(StringUtils.isBlank(dmpid) || "null".equals(dmpid)){
            return R.failure().msg("dmpid不能为空");
        }

        Map<String, Object> baseParamsMap = GetUrlParam.queryStrToMap(queryString);
        baseParamsMap.remove("channelId");
        baseParamsMap.remove("dmpid");

        Map<String, Object> channelDetail = redisCache.getCacheMapValue(CLASSESEN+"Cache", channelId);

        if(channelDetail == null){
            return R.failure().msg("channelId不正确");
        }
        if("0".equals(channelDetail.get("isopen")+"")){
            return R.failure().msg("channelId未开启");
        }
        String callbackClientId = channelDetail.get("callback_clientid") + "";
        String callbackSecretkey = channelDetail.get("callback_secretkey") + "";
        String url = channelDetail.get("request_address") + "";
        String requestType = channelDetail.get("request_type") + "";
        String requestAddress = GetUrlParam.getRequestAddress(url);
        String staticParameters = GetUrlParam.TruncateUrlPage(url);
        Map<String, Object> staticParamsMap = GetUrlParam.queryStrToMap(staticParameters);
        baseParamsMap.putAll(staticParamsMap);


        String ua = baseParamsMap.get("ua") + "";
        String ip = baseParamsMap.get("ip") + "";
        if(StringUtils.isNotBlank(ua) && !"null".equals(ua)){
            ua = URLDecoder.decode(ua, Constants.UTF8);
        }else{
            ua = null;
        }
        if(StringUtils.isNotBlank(ip) && !"null".equals(ip)){
        }else{
            ip = null;
        }

        String nu = getCallback(request, channelId, dmpid, baseParamsMap, callbackClientId, callbackSecretkey);
        baseParamsMap.put("callback_url", URLEncoder.encode(nu, Constants.UTF8));
        String signature =  DigestUtils.md5DigestAsHex(("access_id="+baseParamsMap.get("access_id")+"&ts="+baseParamsMap.get("ts") + SECRET).getBytes(Constants.UTF8)).toLowerCase();
        baseParamsMap.put("signature", signature);
        baseParamsMap.put("request_id", IdUtils.fastSimpleUUID());

        List<String> tempList = new ArrayList<>();
        for(String key: baseParamsMap.keySet()){
            tempList.add(key+"="+baseParamsMap.get(key));
        }
        String requestParameters = String.join("&", tempList);
        String reportResultsStr = "";
        if("POST".equals(requestType)){
            reportResultsStr = HttpUtils.sendPost(requestAddress, requestParameters, ip, ua);
        }else{
            reportResultsStr = HttpUtils.sendGet(requestAddress, requestParameters, ip, ua);
        }

        JSONObject reportResults = null;
        try {
            reportResults = JSONObject.parseObject(reportResultsStr);
            return reportResults==null?"":reportResults;
        }catch (Exception e){
            e.printStackTrace();
        }
        return reportResultsStr;
    }

    private String getCallback(HttpServletRequest request, String channelId, String dmpid, Map<String, Object> baseParamsMap, String callbackClientId, String callbackSecretkey) throws Exception {
        LinkedHashMap<String, String> callbackMap = new LinkedHashMap<>();
        callbackMap.put("cid", getMapValue(baseParamsMap, "cid"));
        callbackMap.put("clientid", callbackClientId);
        callbackMap.put("idfa", getMapValue(baseParamsMap, "idfa"));
        //下游没有imei, 但是有imei_md5
        callbackMap.put("imei", getMapValue(baseParamsMap, "imei_md5"));
        //下游的mac是进行MD5加密过的就是上游的mac_md5
        callbackMap.put("mac", getMapValue(baseParamsMap, "mac_md5"));
        callbackMap.put("os", getMapValue(baseParamsMap, "os"));
        //sid是下游给的click_id。 代表请求标识
        callbackMap.put("sid", getMapValue(baseParamsMap, "click_id"));
        //stime为上报时间戳。 上传过来的参数为ts
        callbackMap.put("stime", getMapValue(baseParamsMap, "ts"));
        //获取当前时间戳 并转化为秒
        callbackMap.put("ts", (System.currentTimeMillis()/1000)+"");

        List<String> tempList = new ArrayList<>();
        for(String key: callbackMap.keySet()){
            tempList.add(key+"="+callbackMap.get(key));
        }
        String callbackParams = String.join("&", tempList);
        String md5 = DigestUtils.md5DigestAsHex((callbackParams+ callbackSecretkey).getBytes(Constants.UTF8)).toUpperCase();

        EncrypDES encrypDES = new EncrypDES();
        String callbackBase = OtherUtils.getServerUrl(request) + "ownOCPXApi2/callback/"+ channelId +"/"+ dmpid +"/";
        String encrypt_u = encrypDES.encrypt(CALLBACK_URLBASE);
        String nu = callbackBase + encrypt_u + "?"+callbackParams+"&sign="+md5;
        return nu;
    }

    private String getMapValue(Map<String, Object> map, String key){
        if(map == null){
            return "";
        }
        if(map.get(key) == null){
            return "";
        }
        return map.get(key)+"";
    }


    @Log(title = "OCPX", businessType = BusinessType.CALLBACK, esIndex = "ocpx_log", saveType = SaveType.ES)
    @RequestMapping("/callback/{channelId}/{dmpid}/{encryptedUrl}")
    public Object callback(HttpServletRequest request, @PathVariable("encryptedUrl") String encryptedUrl) throws Exception {
        String queryString = request.getQueryString();
        Map<String, Object> queryMap = GetUrlParam.queryStrToMap(queryString);
        String eventType = queryMap.get("event_type") + "";
        if("0".equals(eventType)){
            queryMap.put("event_type", 1);
        }else if("1".equals(eventType)) {
            queryMap.put("event_type", 2);
        }else if("2".equals(eventType)) {
            queryMap.put("event_type", 3);
        }else if("3".equals(eventType)) {
            queryMap.put("event_type", 1);
        }else if("4".equals(eventType)) {
            queryMap.put("event_type", 5);
        }else {
            queryMap.put("event_type", 1);
        }
        List<String> tempList = new ArrayList<>();
        for(String key: queryMap.keySet()){
            tempList.add(key+"="+queryMap.get(key));
        }
        queryString = String.join("&", tempList);
        EncrypDES encrypDES = new EncrypDES();
        String requestAddress = encrypDES.decrypt(encryptedUrl);
        String resultStr = HttpUtils.sendGet(requestAddress, queryString);
        try {
            JSONObject resultJson = JSON.parseObject(resultStr);
            return resultJson==null?"":resultJson;
        }catch (Exception e){
            e.printStackTrace();
        }
        return resultStr;
    }





    // 新下游
    @Log(title = "OCPX", businessType = BusinessType.ESCALATION, esIndex = "ocpx_log", saveType = SaveType.ES)
    @RequestMapping("/sendCommon")
    public Object sendCommon(HttpServletRequest request) throws Exception {
        String queryString = request.getQueryString();
        String channelId = request.getParameter("channelId");
        String dmpid = request.getParameter("dmpid");
        if(StringUtils.isBlank(channelId) || "null".equals(channelId)){
            return R.failure().msg("channelId不能为空");
        }
        if(StringUtils.isBlank(dmpid) || "null".equals(dmpid)){
            return R.failure().msg("dmpid不能为空");
        }

        Map<String, Object> baseParamsMap = GetUrlParam.queryStrToMap(queryString);
        baseParamsMap.remove("channelId");
        baseParamsMap.remove("dmpid");

        Map<String, Object> channelDetail = redisCache.getCacheMapValue(CLASSESEN+"Cache", channelId);

        if(channelDetail == null){
            return R.failure().msg("channelId不正确");
        }
        if("0".equals(channelDetail.get("isopen")+"")){
            return R.failure().msg("channelId未开启");
        }
        String url = channelDetail.get("request_address") + "";
        String requestType = channelDetail.get("request_type") + "";
        String requestAddress = GetUrlParam.getRequestAddress(url);
        String staticParameters = GetUrlParam.TruncateUrlPage(url);
        Map<String, Object> staticParamsMap = GetUrlParam.queryStrToMap(staticParameters);
        baseParamsMap.putAll(staticParamsMap);


        String ua = baseParamsMap.get("ua") + "";
        String ip = baseParamsMap.get("ip") + "";
        if(StringUtils.isNotBlank(ua) && !"null".equals(ua)){
            ua = URLDecoder.decode(ua, Constants.UTF8);
        }else{
            ua = null;
        }
        if(StringUtils.isNotBlank(ip) && !"null".equals(ip)){
        }else{
            ip = null;
        }

        String callbackUrl = URLDecoder.decode(baseParamsMap.get("callback_url") + "", Constants.UTF8);
        String callbackUrlRequestAddress = GetUrlParam.getRequestAddress(callbackUrl);
        String callbackUrlStaticParameters = GetUrlParam.TruncateUrlPage(callbackUrl);


        EncrypDES encrypDES = new EncrypDES();
        String callbackBase = OtherUtils.getServerUrl(request) + "ownOCPXApi2/callbackCommon/"+ channelId +"/"+ dmpid +"/";
        String encrypt_u = encrypDES.encrypt(callbackUrlRequestAddress);
        String nu = callbackBase + encrypt_u + "?"+callbackUrlStaticParameters;
        baseParamsMap.put("callback_url", URLEncoder.encode(nu, Constants.UTF8));
        String signature =  DigestUtils.md5DigestAsHex(("access_id="+baseParamsMap.get("access_id")+"&ts="+baseParamsMap.get("ts") + SECRET).getBytes(Constants.UTF8)).toLowerCase();
        baseParamsMap.put("signature", signature);

        List<String> tempList = new ArrayList<>();
        for(String key: baseParamsMap.keySet()){
            tempList.add(key+"="+baseParamsMap.get(key));
        }
        String requestParameters = String.join("&", tempList);
        String reportResultsStr = "";
        if("POST".equals(requestType)){
            reportResultsStr = HttpUtils.sendPost(requestAddress, requestParameters, ip, ua);
        }else{
            reportResultsStr = HttpUtils.sendGet(requestAddress, requestParameters, ip, ua);
        }

        JSONObject reportResults = null;
        try {
            reportResults = JSONObject.parseObject(reportResultsStr);
            return reportResults==null?"":reportResults;
        }catch (Exception e){
            e.printStackTrace();
        }
        return reportResultsStr;
    }




    @Log(title = "OCPX", businessType = BusinessType.CALLBACK, esIndex = "ocpx_log", saveType = SaveType.ES)
    @RequestMapping("/callbackCommon/{channelId}/{dmpid}/{encryptedUrl}")
    public Object callbackCommon(HttpServletRequest request, @PathVariable("encryptedUrl") String encryptedUrl) throws Exception {
        String queryString = request.getQueryString();
        EncrypDES encrypDES = new EncrypDES();
        String requestAddress = encrypDES.decrypt(encryptedUrl);
        String resultStr = HttpUtils.sendGet(requestAddress, queryString);
        try {
            JSONObject resultJson = JSON.parseObject(resultStr);
            return resultJson==null?"":resultJson;
        }catch (Exception e){
            e.printStackTrace();
        }
        return resultStr;
    }


}
